package com.rivues.module.platform.web.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeMeasure;
import com.rivues.module.platform.web.model.CubeMetadata;
import com.rivues.module.platform.web.model.Database;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.TableTask;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.data.DatabaseMetaDataHandler;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.serialize.JSON;

@Controller  
@RequestMapping("/{orgi}/api/cube")  
public class CubeAPIController extends Handler{
	private final Logger log = LoggerFactory.getLogger(CubeAPIController.class); 
	/**
	 * 
	 * @param request
	 * @param response
	 * @param orgi
	 * @throws IOException
	 */
    @RequestMapping(value="/getDBSourceListJSON" , name="getDBSourceListJSON" , type="api",subtype="cube")
	public void getDBSourceListJSON(HttpServletRequest request ,HttpServletResponse response,@PathVariable String orgi) throws IOException {
    	List<Database> databaseList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Database.class).add(Restrictions.eq("orgi", orgi))) ;
    	List<Map<String, String>> list = new ArrayList<Map<String,String>>();
    	Map<String, String> map = null;
    	Database db = null;
    	for (int i = 0; i < databaseList.size(); i++) {
    		db = databaseList.get(i);
			map = new HashMap<String, String>();
			map.put("id", db.getId());
			map.put("name", db.getName());
			if(db.getName()!=null&&!"".equals(db.getName()))
			list.add(map);
		}
    	response.setContentType("text/html;charset=UTF-8");
    	PrintWriter writer = response.getWriter();
    	writer.write(JSON.toJSONString(list));
	}
    
    @RequestMapping(value="/cubepublish" , name="cubepublish" , type="api",subtype="cube")
	public void cubepublish(HttpServletRequest request ,HttpServletResponse response,@PathVariable String orgi,@Valid String isRecover,@Valid String publishcubejson,@Valid String dbsourceid,@Valid boolean freshetl) throws Exception {
    	publishcubejson = RivuTools.decryption(publishcubejson);
    	response.setContentType("text/html;charset=UTF-8");
    	
    	PrintWriter writer = response.getWriter();
    	PublishedCube publishCube  = JSON.parseObject(publishcubejson , PublishedCube.class);
    	Cube cube = publishCube.getCube();
    	publishCube.setId(null) ;
		String cubeid= cube.getId();
    	if("0".equals(dbsourceid)){//创建数据库连接
    		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Database.class).add(Restrictions.eq("id", cube.getDb())).add(Restrictions.eq("orgi", orgi))) ;
    		if(count>0){
    			writer.write("dbSource_exist");
    			return;
    		}else{
    			super.getService().saveIObject(cube.getDb());
    		}
    	}else{
    		Database database = (Database) super.getService().getIObjectByPK(Database.class, dbsourceid) ;
    		publishCube.setDbid(database.getId()) ;
    		cube.setDb(dbsourceid) ;
    		for(CubeMetadata metadata  : cube.getMetadata()){
    			metadata.getTb().setDatabase(database) ;
    		}
    		publishCube.setCubecontent(JSON.toJSONString(cube)) ;
    	}
    	
    	
    	List<PublishedCube> pbCubeList = super.getService().findPageByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("dataid", cubeid)).add(Restrictions.eq("orgi", orgi)).addOrder(Order.desc("dataversion")) , 1 , 1) ;
    	if(pbCubeList.size()>0){
    		int maxVersion = pbCubeList.get(0).getDataversion() ;
    		if("yes".equals(isRecover)){
    			publishCube.setId(pbCubeList.get(0).getId()) ;
    			super.getService().updateIObject(publishCube) ;
        	}else{
        		publishCube.setDataversion(maxVersion+1) ;
        		super.getService().saveIObject(publishCube) ;
        	}
    	}else{
    		publishCube.setDataversion(1) ;
    		super.getService().saveIObject(publishCube) ;
    	}
    	if(freshetl){
    		List<JobDetail> joblist = super.getService().findAllByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("taskid", publishCube.getId())).add(Restrictions.eq("orgi", orgi))) ;
    		if(joblist.size()>0){
    			List<TableTask> tableTaskList = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(TableTask.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("id", joblist.get(0).getCrawltask())))) ;
    			if(tableTaskList.size()>0){
    				TableTask task = tableTaskList.get(0) ;
    				task.setUserpage(true);
    				task.setDatasql(DatabaseMetaDataHandler.getCubeSQL(cube , orgi , task));
    				super.getService().updateIObject(task);
    			}
    		}
    	}
	}
}


























